import React, {Component} from 'react';

import {
    View,
    Modal,
    ScrollView,
    FlatList,
    Text,
    TouchableOpacity,
    StyleSheet,
    Dimensions,
    ListView,
    Image, ActivityIndicator,
} from 'react-native';
import IparImageView from "../custom/IparImageView";
import StyleUtils from "../res/styles/StyleUtils";
import IparNetwork, {SERVER_TYPE} from "../httpUtils/IparNetwork";
import I18n from "../res/language/i18n";
import CommonUtils from "../common/CommonUtils";
import GoodsPage from "../pages/common/GoodsPage";
import GoodsIsBuyPage from "../pages/common/GoodsIsBuyPage";

const {width} = Dimensions.get('window');
export default class ProductAdvertising extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();

        this.state = {
            data: [],
            goodsData: null,
        }
    }


    componentDidMount() {
        const {userData} = this.props;
        this.getProducts(userData);
    }


    // componentDidUpdate(nexProps) {
    //     const nexUserData = nexProps.userData;
    //     const userData = this.props.userData;
    //
    //     if (!nexUserData) return;
    //     if (!userData) return;
    //     if (!nexUserData.user_rank) return;
    //     if (!userData.user_rank) return;
    //
    //     if (nexUserData.user_id !== userData.user_id) {
    //         this.getProducts(nexUserData);
    //     }
    // }

    getProducts(userData) {
        if (!userData) return;
        if (!userData.country) return;
        let goodsId = null;
        if (userData.is_reg_pack === 0) {
            goodsId = userData.user_rank ? userData.user_rank.reg_goods_id : '';
        } else if (userData.is_buy === 0) {
            goodsId = userData.user_rank ? userData.user_rank.sell_goods_id : '';
        }
        if (!goodsId) return;

        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                this.swap_amount = JSON.parse(result).swap_amount;
                this.currencyCode = JSON.parse(result).currency_code;
                this.iparNetwork.getRequest(SERVER_TYPE.goods + 'countryGoods?', 'goods_id=' + goodsId + '&country=' + userData.country)
                    .then((result) => {
                        if (result.code === 200) {
                            let data = result.data.goods;
                            if (data.length > 0) {
                                this.props.requestClose && this.props.requestClose(true);
                                this.setState({
                                    data,
                                    goodsData: result.data,
                                });
                            }
                        }
                    });
            });
    }


    _renderItem(item, isOne) {


        let goodsName = item.goods_local_name;
        if (this.state.country === 'CN') {
            if (I18n.locale === 'uy') {
                goodsName = item.goods_name;
            }
        } else {
            if (I18n.locale === 'en') {
                goodsName = item.goods_name;
            }
        }


        return <TouchableOpacity
            onPress={() => {
                this.props.requestClose && this.props.requestClose(false);
                this.props.nav.push({
                    component: GoodsPage,
                    name: 'GoodsPage',
                    params: {
                        goodsInfo: item
                    }
                });
            }}
            style={[{width: isOne ? '100%' : '50%',}, isOne && {padding: 16}]}>

            <IparImageView
                width={'100%'}
                height={width / 3}
                url={item.image}
            />


            <Text
                numberOfLines={2}
                style={[{fontSize: 12, color: '#464646', marginRight: 8},
                    StyleUtils.smallFont]}>{goodsName}</Text>
            <Text style={[{fontSize: 16, color: 'black', marginRight: 8}]}>
                {(item.goods_pv * this.swap_amount).toFixed(0) + ' ' + this.currencyCode}
            </Text>

        </TouchableOpacity>
    }

    renderItem() {

        const {data} = this.state;

        if (data.length <= 0) return;
        if (data.length == 1)
            return this._renderItem(data[0], true);
        else
            return <FlatList
                numColumns={2}
                columnWrapperStyle={styles.gridListStyle}
                keyExtractor={(item, index) => index}
                renderItem={(item) => this._renderItem(item.item)}
                data={data}/>
    }


    onPress() {

        this.props.requestClose && this.props.requestClose(false);
        if (this.state.data.length === 1) {
            this.props.nav.push({
                component: GoodsPage,
                name: 'GoodsPage',
                params: {
                    goodsInfo: this.state.data[0]
                }
            });
        } else
            this.props.nav.push({
                component: GoodsIsBuyPage,
                name: 'GoodsIsBuyPage',
                params: {
                    goodsData: this.state.goodsData
                }
            })

    }

    render() {

        let {visible} = this.props;

        return (
            <Modal
                animationType='fade'
                transparent={true}
                visible={visible}
                onRequestClose={() => this.props.requestClose && this.props.requestClose(false)}>


                <View style={[styles.boxStyle]}>

                    <View style={[styles.itemBox]}>

                        <Text style={[styles.title, {marginBottom: 8}]}>{I18n.t('b.productAdvertisingMsj')}</Text>

                        {this.renderItem()}

                        <View style={[StyleUtils.rowDirection, {alignSelf: 'flex-end', marginTop: 30}]}>
                            <TouchableOpacity onPress={() => {
                                this.props.requestClose && this.props.requestClose(false);
                            }} style={[{padding: 8, marginRight: 16}]}>
                                <Text>Cancel</Text>
                            </TouchableOpacity>

                            {<TouchableOpacity
                                onPress={() => {
                                    this.onPress();
                                }}
                                style={[styles.submitBtn,]}>
                                <Text style={[{color: 'white',}]}>{I18n.t('b.activatedNow')}</Text>
                            </TouchableOpacity>}

                        </View>

                    </View>
                </View>


            </Modal>
        );
    }

}
const styles = StyleSheet.create({
    boxStyle: {
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 4,
    },

    itemBox: {
        backgroundColor: 'white',
        borderRadius: 10,
        width: '85%',
        padding: 16,
        maxHeight: '85%',
    },


    gridListStyle: {
        marginLeft: 10,
        marginRight: 10,
        marginBottom: 16,
    },
    submitBtn: {
        backgroundColor: 'black',
        padding: 8,
        borderRadius: 4,
    },
    title: {
        fontSize: 16,
        paddingBottom: 8,
        fontWeight: 'bold',
    },
});
